import {EventEmitter, Injectable} from '@angular/core';
import {Http, URLSearchParams} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';

@Injectable()
export class ProductService {

  searchEvent:EventEmitter<ProductSearchParams> = new EventEmitter();

  constructor(private http:Http) { }

  getAllCategories(): string[] {
    return ["电子产品","硬件产品","图书"];
  }

  // 返回所有产品
  getProducts(): Observable<Product[]>{
    return this.http.get("/api/products").map(res => res.json());
  }

  // 根据ID查找相对应的数据
  getProduct(id:number): Observable<Product> {
    return this.http.get("/api/products/"+id).map(res => res.json());
  }

  // 获取商品评论信息
  getCommentsForProductId(id:number): Observable<Comment[]> {
    return this.http.get("/api/products/"+id+"/comments").map(res => res.json());
  }

  // 查询商品
  search(params: ProductSearchParams): Observable<Product[]> {
    return this.http.get("/api/products", {search: this.encodeParams(params)}).map(res => res.json());
  }

  private encodeParams(params: ProductSearchParams) {
    return Object.keys(params)
      .filter(key => params[key])
      .reduce((sum:URLSearchParams, key:string) => {
        sum.append(key, params[key]);
        return sum;
      }, new URLSearchParams());
  }

}

// 搜索参数
export class ProductSearchParams {
  constructor(
    public title:string,
    public price:number,
    public category:string
  ){}
}

export class Product {
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categories: Array<string>
  ) { }
}

export class Comment {
  constructor(
    public id: number,
    public productId: number,
    public timestamp: string,
    public user: string,
    public rating: number,
    public content: string
  ) { }
}
